from datetime import datetime

from flask import Blueprint, render_template, jsonify, request
from ..models.tablemodel import Memos
from utils.model_to_list import model2list

me_bp = Blueprint('memo', __name__)


@me_bp.route('/memos')
def memos():
    return render_template("memo.html")


# 返回备忘录列表数据
@me_bp.route('/api/memos', methods=['GET'])
def get_memos():
    results = Memos().find_memos_by_user()
    memos_list = model2list(results)
    if len(memos_list) > 0:
        for memo in memos_list:
            memo['preview'] = memo.get('content')[:18] + '...'
    return jsonify(memos_list)


@me_bp.route('/api/memos', methods=['POST'])
def create_memo():
    data = request.get_json()
    title = data.get('title')
    content = data.get('content')
    memo = Memos().insert_memo(title=title, content=content)
    memo_dict = memo.to_dict()
    memo_dict['preview'] = memo_dict.get('content')[:18] + '...'
    return jsonify(memo_dict)


@me_bp.route('/api/memos/<int:memo_id>', methods=['GET'])
def get_memo(memo_id):
    memo = Memos()
    row = memo.find_memo_by_id(memo_id)
    memo_result = row.to_dict()
    memo_result['preview'] = memo_result.get('content')[:18] + '...'
    return jsonify(memo_result)


@me_bp.route('/api/memos/<int:memo_id>', methods=['PUT'])
def update_memo(memo_id):
    memo = Memos()
    row = memo.find_memo_by_id(memo_id)
    if row is None:
        return jsonify({'error': '备忘录不存在'}), 404
    else:
        title = request.json.get('title', row.title)
        content = request.json.get('content', row.content)
        update_time = datetime.now().isoformat()
        modified_memo = memo.update_memo(memo_id, title, content, update_time)
        modified_memo = modified_memo.to_dict()
        preview = content[:18] + '...'
        modified_memo['preview'] = preview
        return jsonify(modified_memo)


@me_bp.route('/api/memos/<int:memo_id>', methods=['DELETE'])
def delete_memo(memo_id):
    memo = Memos()
    row = memo.find_memo_by_id(memo_id)
    if row is None:
        return jsonify({'error': '备忘录不存在'}), 404
    else:
        memo.delete_memo_by_id(memo_id)
        return jsonify({'success': True})

@me_bp.route('/memos/help')
def memos_help():
    return '编辑、分栏、预览切换快捷键：F2，F3, F4'
